package com.pig.graduate.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig.graduate.common.constant.Constant;
import com.pig.graduate.common.exception.MyException;
import com.pig.graduate.domain.sys.SysMenu;
import com.pig.graduate.domain.sys.SysRole;
import com.pig.graduate.domain.sys.SysRoleMenu;
import com.pig.graduate.domain.sys.SysUserRole;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.sys.SysMenuService;
import com.pig.graduate.service.sys.SysRoleMenuService;
import com.pig.graduate.service.sys.SysRoleService;
import com.pig.graduate.service.sys.SysUserRoleService;
import com.pig.graduate.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统角色Controller控制器
 */
@Api(value = "role",tags = "角色模块")
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据条件分页查询角色列表
     * @param sysRole
     * @return
     */
    @ApiOperation(value = "角色列表",notes = "角色列表")
    @PostMapping("/list")
//    @PreAuthorize("hasAuthority('system:role:list')")
    public MyResult list(@RequestBody SysRole sysRole){
        Page<SysRole> rolePage = new Page<>(sysRole.getPageNum(),sysRole.getPageSize());
        Page<SysRole> page = new LambdaQueryChainWrapper<SysRole>(sysRoleService.getBaseMapper())
                .like(SysRole::getName, sysRole.getName())
                .like(SysRole::getCode, sysRole.getCode())
                .select(SysRole::getId,SysRole::getName,SysRole::getCode,SysRole::getCreateTime,SysRole::getUpdateTime)
                .page(rolePage);
        return MyResult.success(page);
    }

    /**
     * 添加或者修改
     * @param sysRole
     * @return
     */
    @ApiOperation(value = "添加或者修改",notes = "添加或者修改")
    @PostMapping("/saveAndUpdate")
//    @PreAuthorize("hasAuthority('system:role:add')"+"||"+"hasAuthority('system:role:edit')")
    public MyResult saveAndUpdate(@RequestBody @Valid SysRole sysRole){
        if(sysRole.getId()==null || sysRole.getId()==0){
            sysRole.setCreateTime(new Date());
            sysRoleService.save(sysRole);
        }else{
            sysRole.setUpdateTime(new Date());
            sysRoleService.updateById(sysRole);
        }
        List<SysRoleMenu> sysRoleMenuList=new ArrayList<>();
        if(sysRole.getMenuIds().length > 0){
            Arrays.stream(sysRole.getMenuIds()).forEach(menuId->{
                SysRoleMenu roleMenu=new SysRoleMenu();
                roleMenu.setMenuId(menuId);
                roleMenu.setRoleId(sysRole.getId());
                sysRoleMenuList.add(roleMenu);
            });
            sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id",sysRole.getId()));
            sysRoleMenuService.saveBatch(sysRoleMenuList);
        }
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询",notes = "根据id查询")
    @GetMapping("/{id}")
//    @PreAuthorize("hasAuthority('system:role:query')")
    public MyResult findById(@PathVariable(value = "id")Integer id){
        SysRole sysRole = sysRoleService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("sysRole",sysRole);
        // List<SysMenu> sysMenuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id=" + id));
        List<SysMenu> list = sysMenuService.getMenuByRoleId(id);
        map.put("menuList",list);
        return MyResult.success(map);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除",notes = "删除")
    @Transactional
    @PostMapping("/delete")
//    @PreAuthorize("hasAuthority('system:role:delete')")
    public MyResult delete(@RequestBody Long[] ids){
        sysRoleService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id",ids));
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return MyResult.success("删除成功");
    }

    /**
     * 获取当前角色的权限菜单
     * @param id
     * @return
     */
    @ApiOperation(value = "获取当前角色的权限菜单",notes = "获取单枪角色的权限菜单")
    @GetMapping("/menus/{id}")
//    @PreAuthorize("hasAuthority('system:role:query')")
    public MyResult menus(@PathVariable(value = "id")Integer id){
        List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
        return MyResult.success().put("menuIdList",menuIdList);
    }

    /**
     * 更新角色权限信息
     * @param id
     * @param menuIds
     * @return
     */
    @ApiOperation(value = "更新角色权限信息",notes = "更新角色权限信息")
    @Transactional
    @PostMapping("/updateMenus/{id}")
//    @PreAuthorize("hasAuthority('system:role:edit')")
    public MyResult updateMenus(@PathVariable(value = "id")Long id,@RequestBody Long[] menuIds){
      List<SysRoleMenu> sysRoleMenuList=new ArrayList<>();
      Arrays.stream(menuIds).forEach(menuId->{
          SysRoleMenu roleMenu=new SysRoleMenu();
          roleMenu.setMenuId(menuId);
          roleMenu.setRoleId(id);
          sysRoleMenuList.add(roleMenu);
      });
      sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id",id));
      sysRoleMenuService.saveBatch(sysRoleMenuList);
      redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
      return MyResult.success();
    }



}
